package com.fzt.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzt.system.convert.SysUserConvert;
import com.fzt.system.domain.entity.SysUserEntity;
import com.fzt.system.domain.param.SysUserParam;
import com.fzt.system.domain.vo.SysUserVO;
import com.fzt.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户管理
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-09
 */
@Service
@AllArgsConstructor
public class SysUserService extends ServiceImpl<SysUserMapper, SysUserEntity> {
    private final SysUserMapper      sysUserMapper;
    private final SysUserRoleService sysUserRoleService;


    public IPage<SysUserVO> selectPage(SysUserParam sysUserParam) {
        Page<SysUserEntity> page = new Page<>(sysUserParam.getPageNum(), sysUserParam.getPageSize());

        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SysUserEntity> wrapper = queryWrapper
                .eq(StringUtils.isNotEmpty(sysUserParam.getRealName()), SysUserEntity::getRealName, sysUserParam.getRealName())
                .eq(StringUtils.isNotEmpty(sysUserParam.getMobile()), SysUserEntity::getMobile, sysUserParam.getMobile())
                .eq(sysUserParam.getGender() != null, SysUserEntity::getGender, sysUserParam.getGender())
                .eq(sysUserParam.getOrgId() != null, SysUserEntity::getOrgId, sysUserParam.getOrgId())
                .eq(sysUserParam.getStatus() != null, SysUserEntity::getStatus, sysUserParam.getStatus());

        Page<SysUserEntity> sysUserEntityPage = sysUserMapper.selectPage(page, wrapper);

        return sysUserEntityPage.convert(SysUserConvert.INSTANCE::convertSysUserVO);
    }


    public SysUserVO getUser(Long userId) {
        SysUserEntity sysUserEntity = sysUserMapper.selectById(userId);
        SysUserVO     sysUserVO     = SysUserConvert.INSTANCE.convertSysUserVO(sysUserEntity);
        List<Long>    roleIdList    = sysUserRoleService.getRoleIdList(userId);
        sysUserVO.setRoleIdList(roleIdList);
        return sysUserVO;
    }


    public void saveUser(SysUserVO sysUserVO) {
        SysUserEntity sysUserEntity = SysUserConvert.INSTANCE.convert(sysUserVO);
        save(sysUserEntity);
        sysUserRoleService.saveOrUpdate(sysUserEntity.getId(), sysUserVO.getRoleIdList());
    }


    public void updateUser(SysUserVO sysUserVO) {
        SysUserEntity sysUserEntity = SysUserConvert.INSTANCE.convert(sysUserVO);
        updateById(sysUserEntity);
        sysUserRoleService.saveOrUpdate(sysUserEntity.getId(), sysUserVO.getRoleIdList());
    }


}
